<?php
namespace App\Api\Controllers;

use App\Models\Order;
use App\Models\StocksTrades;
use App\Models\User;
use App\Api\Requests\StocksTradesRequest;
use Dingo\Api\Http\Request;
use App\Models\UserLog;

use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\DB;
class StocksTradesController extends Controller
{
    public function index(StocksTrades $stocksTrades){
        $state= $_GET["state"];
        //$verifyData = \Cache::get("aaa");
        return $this->success($stocksTrades->where('order_status',0)->where("rise_fall",$state)->orderBy('id','desc')->get());
    }
    //购买
   public function purchase(StocksTrades $stocksTrades ,User $user){
       $order_id = $_GET["s_id"];
       $order=$stocksTrades->where("order_status",0)->where("id",$order_id)->first();
       $price=  $order->number*$order->price;
       if($price> $this->user()->balance){
           return $this->error('余额不足');
       }
       $stocksTrades->seller_uid = 81;
       $stocksTrades->order_status = 1;
       if( DB::table('stocks_trades')->where("Id",$order_id)->update(['seller_uid'=>91,'order_status'=>1])){
           //扣减BTC
           (new UserLog())->change(-$price,81,'balance',43,'会员购买股权');
           DB::table('users')->where('id', '=', $this->user()->id)->update(['balance' => $this->user()->balance-$price]);
       }
   }

   //出售
    public  function sell(StocksTrades $stocksTrades ,StocksTradesRequest $request,User $user){
        if($request->number < 1){
            return $this->error('股权一个起卖');
        }
        if($request->number > $this->user()->stock){
            return $this->error('可出售股权不足');
        }
        $stocksTrades->member_id = 81;
        $stocksTrades->rise_fall = 1;
        $stocksTrades->number = $request->number;
        $stocksTrades->price = $request->price;
        $stocksTrades->order_status = 0;
        if($stocksTrades->save()){
            //扣减BTC
            (new UserLog())->change(-$stocksTrades->number,81,'stock',43,'会员出售股权');
            DB::table('users')->where('id', '=', 81)->update(['stock' => 100-$stocksTrades->number]);
        }

    }
}